package com.fudan.adse.service.impl;

import com.fudan.adse.domain.po.Wallet;
import com.fudan.adse.domain.po.WalletExample;
import com.fudan.adse.exception.ApiException;
import com.fudan.adse.mbg.mapper.WalletMapper;
import com.fudan.adse.service.WalletService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author Jerry Zhang
 * create: 2022-11-24 14:06
 */
@Slf4j
@Service
public class WallServiceImpl implements WalletService {
    @Autowired
    private WalletMapper walletMapper;

    @Override
    public Wallet getWalletByUsername(String username) {
        WalletExample walletExample = new WalletExample();
        walletExample.createCriteria().andUsernameEqualTo(username);
        List<Wallet> wallets = walletMapper.selectByExample(walletExample);
        if (wallets.isEmpty()) {
            log.info("钱包不存在，自动初始化");
            Wallet wallet = new Wallet();
            wallet.setUsername(username);
            wallet.setIncome(BigDecimal.ZERO);
            wallet.setOutcome(BigDecimal.ZERO);
            wallet.setBalance(BigDecimal.ZERO);
            wallet.setSign("");
            if (walletMapper.insert(wallet) > 0) {
                return wallet;
            }
            throw new ApiException("初始化钱包失败");
        }
        return wallets.get(0);
    }

    @Override
    public int updateByPrimaryKeySelective(Wallet wallet) {
        return walletMapper.updateByPrimaryKeySelective(wallet);
    }
}
